package com.gymmsystem.GYMMSystem.controller;

import com.gymmsystem.GYMMSystem.common.Result;
import com.gymmsystem.GYMMSystem.entity.UserMessage;
import com.gymmsystem.GYMMSystem.service.UserMessageService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/user-messages")
public class UserMessageController {

    @Autowired
    private UserMessageService userMessageService;
    private static final Logger log = LoggerFactory.getLogger(UserMessageController.class);

    /**
     * 获取用户的所有消息
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Result<List<UserMessage>>> getUserMessages(@PathVariable Long userId) {
        try {
            List<UserMessage> messages = userMessageService.findMessagesByUserId(userId);
            return ResponseEntity.ok(Result.success(messages));
        } catch (Exception e) {
            log.error("获取用户消息失败，用户ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("获取用户消息失败"));
        }
    }

    /**
     * 获取用户的未读消息数量
     */
    @GetMapping("/user/{userId}/unread-count")
    public ResponseEntity<Result<Integer>> getUnreadCount(@PathVariable Long userId) {
        try {
            int count = userMessageService.countUnreadMessages(userId);
            return ResponseEntity.ok(Result.success(count));
        } catch (Exception e) {
            log.error("获取未读消息数量失败，用户ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("获取未读消息数量失败"));
        }
    }

    /**
     * 根据ID获取消息详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result<UserMessage>> getMessageById(@PathVariable Long id) {
        try {
            UserMessage message = userMessageService.getMessageById(id);
            if (message != null) {
                return ResponseEntity.ok(Result.success(message));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(Result.error("消息不存在"));
            }
        } catch (Exception e) {
            log.error("获取消息详情失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("获取消息详情失败"));
        }
    }

    /**
     * 标记消息为已读
     */
    @PutMapping("/{id}/read")
    public ResponseEntity<Result<Boolean>> markAsRead(@PathVariable Long id) {
        try {
            boolean success = userMessageService.markAsRead(id);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "消息已标记为已读"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("标记消息为已读失败"));
            }
        } catch (Exception e) {
            log.error("标记消息为已读失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("标记消息为已读失败"));
        }
    }

    /**
     * 标记用户所有消息为已读
     */
    @PutMapping("/user/{userId}/read-all")
    public ResponseEntity<Result<Boolean>> markAllAsRead(@PathVariable Long userId) {
        try {
            boolean success = userMessageService.markAllAsRead(userId);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "所有消息已标记为已读"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("标记所有消息为已读失败"));
            }
        } catch (Exception e) {
            log.error("标记所有消息为已读失败，用户ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("标记所有消息为已读失败"));
        }
    }

    /**
     * 创建新消息
     */
    @PostMapping("/insert")
    public ResponseEntity<Result<Long>> createMessage(@RequestBody UserMessage userMessage) {
        try {
            Long newId = userMessageService.createMessage(userMessage);
            if (newId != null) {
                return ResponseEntity.ok(Result.success(newId, "消息创建成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("消息创建失败"));
            }
        } catch (Exception e) {
            log.error("创建消息失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("创建消息失败"));
        }
    }

    /**
     * 删除用户的所有消息
     */
    @DeleteMapping("/user/{userId}")
    public ResponseEntity<Result<Boolean>> deleteMessagesByUserId(@PathVariable Long userId) {
        try {
            boolean success = userMessageService.deleteMessagesByUserId(userId);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "用户消息删除成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("用户消息删除失败"));
            }
        } catch (Exception e) {
            log.error("删除用户消息失败，用户ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("删除用户消息失败"));
        }
    }

    /**
     * 删除用户的已读消息
     */
    @DeleteMapping("/user/{userId}/read")
    public ResponseEntity<Result<Boolean>> deleteReadMessages(@PathVariable Long userId) {
        try {
            boolean success = userMessageService.deleteReadMessages(userId);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "已读消息删除成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("已读消息删除失败"));
            }
        } catch (Exception e) {
            log.error("删除已读消息失败，用户ID: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("删除已读消息失败"));
        }
    }

    /**
     * 生成课程预约成功消息
     */
    @PostMapping("/booking")
    public ResponseEntity<Result<Boolean>> createBookingMessage(
            @RequestParam Long userId,
            @RequestParam String content,
            @RequestParam Long reservationId) {
        try {
            boolean success = userMessageService.insertBookingMessage(userId, content, reservationId);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "预约消息生成成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("预约消息生成失败"));
            }
        } catch (Exception e) {
            log.error("生成预约消息失败，用户ID: {}，预约ID: {}", userId, reservationId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("生成预约消息失败"));
        }
    }

    /**
     * 生成课程取消预约消息
     */
    @PostMapping("/cancel")
    public ResponseEntity<Result<Boolean>> createCancelMessage(
            @RequestParam Long userId,
            @RequestParam String content,
            @RequestParam Long reservationId) {
        try {
            boolean success = userMessageService.insertCancelMessage(userId, content, reservationId);
            if (success) {
                return ResponseEntity.ok(Result.success(true, "取消预约消息生成成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("取消预约消息生成失败"));
            }
        } catch (Exception e) {
            log.error("生成取消预约消息失败，用户ID: {}，预约ID: {}", userId, reservationId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("生成取消预约消息失败"));
        }
    }
}